﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Yqd.Enm;
using System.IO;
using OfficeOpenXml;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxSchemeController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxSchemeController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        /// <summary>
        /// 添加工作方案
        /// </summary>
        /// datas:{SchemeApproval:{Leader:"",Dept:"",DeptLeader:""},
        /// Scheme:[{JobTarget:"",CooperativeUnit:"",JobType:"",
        /// Plan:[{Measure:"",CompleteTime:""}]}]
        /// <returns></returns>
        [User]
        public IActionResult Add()
        {
            var TaskID = Form.GetLong("TaskID");
            var AssignID = Form.GetInt("AssignID");
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var datas = Form.GetString("datas");
            var ret = 0;
            if (datas.HasValue())
            {
                var assign = ctx.Yqd_Assign.SingleOrDefault(x => x.AssignID == AssignID);
                var user = ctx.Yqd_User.Where(x => x.EmployeeCode == assign.EmployeeCode).SingleOrDefault();

                var ItemID = SuperviseID;
                var ItemType = 事项类型.钉办督导;
                string headtitle = "", text = "";
                List<string> AccountId = new List<string>();
                var IsJb = false;
                if (SuperviseID > 0)
                {
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                    if (s != null)
                    {
                        headtitle = "领导督导";
                        //var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                        //if(!string.IsNullOrWhiteSpace(user.RealtionEmployeeCode))
                        //{
                        //    var arrayEmployee = user.RealtionEmployeeCode.Split(",");
                        //    var userList = ctx.Yqd_User.Where(it => it.AccountId > 0 && it.Status == 用户状态.使用中 && arrayEmployee.Contains(it.EmployeeCode));
                        //    AccountId = userList.Select(it => it.AccountId.ToString()).ToList();
                        //}
                        AccountId.Add(user.AccountId.ToString());
                    }
                }
                if (CoordinateID > 0)
                {
                    ItemID = CoordinateID;
                    ItemType = 事项类型.协同管理;
                    var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == ItemID);
                    if (c != null)
                    {
                        headtitle = "领导协调";
                        text = "协调内容  " + c.Item;
                    }
                }
                if (eSuperviseID > 0)
                {
                    ItemID = eSuperviseID;
                    ItemType = 事项类型.精准督查;
                    var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                    if (s != null)
                    {
                        headtitle = "精准督查";
                        //var user = ctx.Yqd_User.Where(x => x.EmployeeCode == s.EmployeeCode).SingleOrDefault();
                        AccountId.Add(user.AccountId.ToString());
                    }
                }
                if (sSuperviseID > 0)
                {
                    ItemID = sSuperviseID;
                    ItemType = 事项类型.专项交办;
                    var s = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                    if (s != null)
                    {
                        headtitle = s.TaskType.ToString();

                        AccountId.Add(user.AccountId.ToString());
                    }
                    IsJb = true;
                }
                switch (ItemType)
                {
                    case 事项类型.钉办督导:
                        var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                        if (s != null && s.Status == 任务状态.已完成)
                        {
                            return this.ToJson(new
                            {
                                success = true,
                                ret = 0
                            });
                        }
                        break;
                    case 事项类型.协同管理:
                        var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == CoordinateID);
                        if (r != null && r.Status == 任务状态.已完成)
                        {
                            return this.ToJson(new
                            {
                                success = true,
                                ret = 0
                            });
                        }
                        break;
                    case 事项类型.精准督查:
                        var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == eSuperviseID);
                        if (e != null && e.Status == 任务状态.已完成)
                        {
                            return this.ToJson(new
                            {
                                success = true,
                                ret = 0
                            });
                        }
                        break;
                    case 事项类型.专项交办:
                        var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == sSuperviseID);
                        if (rs != null && rs.Status == 任务状态.已完成)
                        {
                            return this.ToJson(new
                            {
                                success = true,
                                ret = 0
                            });
                        }
                        break;
                }
                ctx.Database.ExecuteSql("Update Yqd_Scheme set IsComplete=0 where AssignID={0}", AssignID);
                var o = JObject.Parse(datas);
                var report = o["SchemeApproval"];
                ctx.Yqd_SchemeApproval.Add(new Yqd_SchemeApproval
                {
                    TaskID = TaskID,
                    AssignID = AssignID,
                    ItemID = ItemID,
                    ItemType = ItemType,
                    Leader = report["Leader"].ToString(),
                    Dept = report["Dept"].ToString(),
                    DeptLeader = report["DeptLeader"].ToString(),
                    Instime = DateTime.Now,
                    EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                    UnitCode = WxUser.LogonInfo.UnitCode,
                    Attachment = report["Attachment"]?.ToString()
                });
                var slst = new List<Yqd_Scheme>();
                var scheme = (JArray)o["Scheme"];
                foreach (var s in scheme)
                {
                    var JobType = int.Parse(s["JobType"].ToString());
                    slst.Add(new Yqd_Scheme
                    {
                        TaskID = TaskID,
                        AssignID = AssignID,
                        ItemID = ItemID,
                        ItemType = ItemType,
                        JobTarget = s["JobTarget"].ToString(),
                        JobType = (工作类型)JobType,
                        CheckStatus = 审核状态.待审,
                        IsComplete = false,
                        Instime = DateTime.Now,
                        EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                        UnitCode = WxUser.LogonInfo.UnitCode
                    });
                }
                ctx.Yqd_Scheme.AddRange(slst);
                ret = ctx.SaveChanges();
                if (ret > 0)
                {
                    var plst = new List<Yqd_JobPlan>();
                    foreach (var s in scheme)
                    {
                        var target = s["JobTarget"].ToString();
                        //var CooperativeUnit = s["CooperativeUnit"]?.ToString();
                        var m = slst.FirstOrDefault(it => it.JobTarget == target);
                        var SchemeID = 0;
                        if (m != null) SchemeID = m.SchemeID;
                        var plan = (JArray)s["Plan"];
                        foreach (var p in plan)
                        {
                            var model = new Yqd_JobPlan
                            {
                                TaskID = TaskID,
                                AssignID = AssignID,
                                ItemID = ItemID,
                                ItemType = ItemType,
                                SchemeID = SchemeID,
                                Measure = p["Measure"].ToString(),
                                CompleteTime = DateTime.Parse(p["CompleteTime"].ToString()),
                                //CooperativeUnit = CooperativeUnit,
                                PlanStatus = 工作计划状态.未完成,
                                Instime = DateTime.Now,
                                EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                                UnitCode = WxUser.LogonInfo.UnitCode
                            };
                            plst.Add(model);
                        }
                    }
                    ctx.Yqd_JobPlan.AddRange(plst);
                    ret = ctx.SaveChanges();
                    if (ret > 0)
                    {
                        var TaskName = "";
                        var tID = TaskID;
                        if (ItemType == 事项类型.专项交办)
                        {
                            tID = 0;
                            var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == TaskID);
                            if (t != null) TaskName = t.Name;
                        }
                        else
                        {
                            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
                            if (task != null) TaskName = task.TaskName;
                        }
                        var l = WxUser.LogonInfo;
                        //关闭通知
                        var msg = ddService.Notification(AccountId, headtitle, tID.ToString(), "任务名称: " + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})报送了工作方案，请及时审核！", true, pushStep: 推送流程.工作流转, unitCode: WxUser.LogonInfo.UnitCode);
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了工作方案通知，返回值：" + msg);
                        TaskLogService.AddLog(IsJb ? ItemID : TaskID, "工作方案报审", IsJb);
                    }
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        /// <summary>
        /// 修改单条工作方案
        /// </summary>
        /// Plan:[{Measure:"",CompleteTime:""}]}]
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult Edit(Yqd_Scheme model)
        {
            var ret = 0;
            var m = ctx.Yqd_Scheme.FirstOrDefault(it => it.SchemeID == model.SchemeID);
            if (m != null)
            {
                m.JobTarget = model.JobTarget;
                m.JobType = model.JobType;
                m.CheckStatus = 审核状态.待审;
                m.CheckTime = null;
                m.ReturnReason = "";
                ret = ctx.SaveChanges();
                if (ret > 0)
                {
                    var IsJb = m.ItemType == 事项类型.专项交办;
                    var TaskID = IsJb ? m.ItemID : m.TaskID;
                    TaskLogService.AddLog(TaskID, "修改了工作方案(" + m.JobTarget + "", IsJb);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var l = WxUser.LogonInfo;
            if (!l.Role.Contains(角色类型.管理员))
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "无权限删除"
                });
            }
            var SchemeID = Form.GetInt("SchemeID");
            var s = ctx.Yqd_Scheme.FirstOrDefault(it => it.SchemeID == SchemeID);
            //delete from Yqd_JobPlan where SchemeID={0};
            var ret = ctx.Database.ExecuteSql("update Yqd_Scheme set IsDel=1 where SchemeID={0};", SchemeID);
            if (ret > 0)
            {
                var IsJb = s.ItemType == 事项类型.专项交办;
                var TaskID = IsJb ? s.ItemID : s.TaskID;
                TaskLogService.AddLog(TaskID, "删除了工作方案(" + s.JobTarget + "", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        /// <summary>
        /// 添加工作计划
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult AddPlan(Yqd_JobPlan model)
        {
            var TaskID = Form.GetLong("TaskID");
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;
            var IsJb = false;
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
                IsJb = true;
            }
            switch (ItemType)
            {
                case 事项类型.钉办督导:
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                    if (s != null && s.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.协同管理:
                    var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == CoordinateID);
                    if (r != null && r.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.精准督查:
                    var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == eSuperviseID);
                    if (e != null && e.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.专项交办:
                    var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == sSuperviseID);
                    if (rs != null && rs.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
            }
            var ps = ctx.Yqd_JobPlan.Where(it => it.SchemeID == model.SchemeID);
            if (!ps.Any(it => it.CompleteTime > model.CompleteTime))
            {
                foreach (var p in ps) p.TimeLine = "";
                var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == model.AssignID);
                if (a != null)
                {
                    model.TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, model.CompleteTime, a.Days);
                }
            }
            model.TaskID = TaskID;
            model.ItemID = ItemID;
            model.ItemType = ItemType;
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                TaskLogService.AddLog(IsJb ? ItemID : TaskID, "添加了工作计划(" + model.Measure + ")", IsJb);
                ctx.Database.ExecuteSql("update Yqd_Scheme set CheckStatus={1},CheckTime=null,ReturnReason='' where SchemeID={0};", model.SchemeID, (int)审核状态.待审);

            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult EditPlan(Yqd_JobPlan model)
        {
            var ret = 0;
            var m = ctx.Yqd_JobPlan.FirstOrDefault(it => it.PlanID == model.PlanID);
            if (m != null)
            {
                var ps = ctx.Yqd_JobPlan.Where(it => it.SchemeID == m.SchemeID);
                if (!ps.Any(it => it.CompleteTime > model.CompleteTime))
                {
                    foreach (var p in ps) p.TimeLine = "";
                    var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == model.AssignID);
                    if (a != null)
                    {
                        model.TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, m.CompleteTime, a.Days);
                    }
                }
                m.Measure = model.Measure;
                m.CompleteTime = model.CompleteTime;
                m.CooperativeUnit = model.CooperativeUnit;
                ret = ctx.SaveChanges();
                if (ret > 0)
                {
                    var IsJb = m.ItemType == 事项类型.专项交办;
                    var TaskID = IsJb ? m.ItemID : m.TaskID;
                    TaskLogService.AddLog(TaskID, "修改了工作计划(" + m.Measure + "", IsJb);
                    ctx.Database.ExecuteSql("update Yqd_Scheme set CheckStatus={1},CheckTime=null,ReturnReason='' where SchemeID={0};", m.SchemeID, (int)审核状态.待审);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult EditApproval(Yqd_SchemeApproval model)
        {
            var ret = 0;
            var m = ctx.Yqd_SchemeApproval.FirstOrDefault(it => it.ApprovalID == model.ApprovalID);
            if (m != null)
            {
                m.Leader = model.Leader;
                m.DeptLeader = model.DeptLeader;
                m.Dept = model.Dept;
                ret = ctx.SaveChanges();
                if (ret > 0)
                {
                    var IsJb = m.ItemType == 事项类型.专项交办;
                    var TaskID = IsJb ? m.ItemID : m.TaskID;
                    TaskLogService.AddLog(TaskID, "修改了工作方案报审", IsJb);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult DelPlan()
        {
            var PlanID = Form.GetInt("PlanID");
            var s = ctx.Yqd_JobPlan.FirstOrDefault(it => it.PlanID == PlanID);
            var ret = ctx.Database.ExecuteSql("delete from Yqd_JobPlan where PlanID={0};", PlanID);
            if (ret > 0)
            {
                var pl = ctx.Yqd_JobPlan.Where(it => it.SchemeID == s.SchemeID).OrderBy(it => it.CompleteTime);
                if (pl.Any())
                {
                    var p = pl.First();
                    var TimeLine = "";
                    var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == s.AssignID);
                    if (a != null)
                    {
                        TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, p.CompleteTime, a.Days);
                    }
                    ctx.Database.ExecuteSql("update Yqd_JobPlan set TimeLine={1} where PlanID={0}", p.PlanID, TimeLine);
                }
                var IsJb = s.ItemType == 事项类型.专项交办;
                var TaskID = IsJb ? s.ItemID : s.TaskID;
                TaskLogService.AddLog(TaskID, "删除了工作计划(" + s.Measure + ")", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        /// <summary>
        /// 工作方案 审核
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [User]
        public IActionResult Check()
        {
            var SchemeID = Form.GetInt("SchemeID");
            var m = ctx.Yqd_Scheme.FirstOrDefault(it => it.SchemeID == SchemeID);
            var ret = 0;
            if (m != null)
            {
                m.CheckStatus = (审核状态)Form.GetInt("CheckStatus");
                m.CheckTime = DateTime.Now;
                if (m.CheckStatus == 审核状态.退回) m.IsComplete = true;
                m.ReturnReason = Form.GetString("Reason");
                ret = ctx.SaveChanges();
                if (ret > 0)
                {
                    if (m.CheckStatus == 审核状态.同意)
                    {
                        //todo:bug
                        var pl = ctx.Yqd_JobPlan.Where(it => it.SchemeID == SchemeID).OrderBy(it => it.CompleteTime).ThenBy(it => it.PlanID);
                        if (pl.Any())
                        {
                            var p = pl.First();
                            if (string.IsNullOrWhiteSpace(p.TimeLine))
                            {
                                var TimeLine = "";
                                var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == m.AssignID);
                                if (a != null)
                                {
                                    TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, p.CompleteTime, a.Days);
                                    ctx.Database.ExecuteSql("update Yqd_JobPlan set TimeLine={1} where PlanID={0}", p.PlanID, TimeLine);
                                }
                            }
                        }
                    }
                    string headtitle = "", text = "";
                    var IsJb = false;
                    string employeeName = "";
                    switch (m.ItemType)
                    {
                        case 事项类型.钉办督导:
                            var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (s != null)
                            {
                                headtitle = "领导督导";
                                text = "督导意见  " + s.Content;

                                var ap = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && it.ItemType == 事项类型.钉办督导).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
                                if (ap != null)
                                {
                                    employeeName = ap.DeptLeader;
                                }
                            }
                            break;
                        case 事项类型.协同管理:
                            var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == m.ItemID);
                            if (c != null)
                            {
                                headtitle = "领导协调";
                                text = "协调内容  " + c.Item;
                            }
                            break;
                        case 事项类型.精准督查:
                            var es = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (es != null)
                            {
                                headtitle = "精准督查";
                                text = "存在问题  " + es.Problem;
                                var ap2 = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && it.ItemType == 事项类型.精准督查).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
                                if (ap2 != null)
                                {
                                    employeeName = ap2.DeptLeader;
                                }
                            }
                            break;
                        case 事项类型.专项交办:
                            var ss = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == m.ItemID);
                            if (ss != null)
                            {
                                headtitle = ss.TaskType.ToString();
                            }

                            var ap3 = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == m.ItemID && (it.ItemType == 事项类型.专项交办 || it.ItemType == 事项类型.专项督查)).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
                            if (ap3 != null)
                            {
                                employeeName = ap3.DeptLeader;
                            }
                            IsJb = true;
                            break;
                    }
                    var TaskName = "";
                    var tID = m.TaskID;
                    if (m.ItemType == 事项类型.专项交办)
                    {
                        tID = 0;
                        var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == m.TaskID);
                        if (t != null) TaskName = t.Name;
                    }
                    else
                    {
                        var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == m.TaskID);
                        if (task != null) TaskName = task.TaskName;
                    }
                    var l = WxUser.LogonInfo;
                    var assign = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == m.AssignID);
                    //关闭通知
                    if (m.CheckStatus == 审核状态.退回)
                    {
                        var msg = ddService.Notification(new List<string>(), headtitle, tID.ToString(), "任务名称: " + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})退回了工作方案，请重新报送！", pushStep: 推送流程.工作退回, unitCode: assign.LeadUnit, employeeNames: new List<string>() { employeeName });
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了退回工作方案通知，返回值：" + msg);
                    }
                    //var msg = ddService.Notification(assign.LeadUnit, headtitle, tID, TaskName, text + "\n" + l.UnitName + "(" + l.Name + ")" + m.CheckStatus + "了(" + m.JobTarget + ")工作方案，请及时查看！");
                    TaskLogService.AddLog(IsJb ? m.ItemID : m.TaskID, m.CheckStatus.ToString() + "了(" + m.JobTarget + ")工作方案", IsJb);
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult GetHistory()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;

            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
            }
            var data = ctx.Database.SqlQuery<Yqd_Scheme>("select * from Yqd_Scheme where [ItemID]={0} and [ItemType]={1} and [CheckStatus]={2} order by [Instime] desc", ItemID, (int)ItemType, (int)审核状态.退回);
            var unit = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var sIDs = data.Select(it => it.SchemeID).ToArray();
            var ps = ctx.Yqd_JobPlan.Where(it => sIDs.Contains(it.SchemeID)).ToList();
            return this.ToJson(new
            {
                success = true,
                totalcount = data.Count(),
                data = data.ToList().Select(it => new
                {
                    it.SchemeID,
                    it.JobTarget,
                    JobType = it.JobType.ToString(),
                    it.ReturnReason,
                    Plan = ps.Where(p => p.SchemeID == it.SchemeID).Select(m => new
                    {
                        m.PlanID,
                        m.Measure,
                        CompleteTime = m.CompleteTime.ToString("yyyy-MM-dd"),
                        CooperativeUnit = unit.FirstOrDefault(p => p.UnitCode == m.CooperativeUnit)?.Name ?? ""
                    })
                })
            });
        }

        [User]
        public ActionResult Urge()
        {
            var PlanID = Form.GetInt("PlanID");
            var msg = Form.GetString("Msg");
            var p = ctx.Yqd_JobPlan.FirstOrDefault(it => it.PlanID == PlanID);
            if (p != null)
            {
                long TaskID = 0;
                var isDd = false;
                switch (p.ItemType)
                {
                    case 事项类型.钉办督导:
                        var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == p.ItemID);
                        if (s != null) TaskID = s.TaskID;
                        break;
                    case 事项类型.协同管理:
                        var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == p.ItemID);
                        if (r != null) TaskID = r.TaskID;
                        break;
                    case 事项类型.精准督查:
                        var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == p.ItemID);
                        if (e != null) TaskID = e.TaskID;
                        break;
                    case 事项类型.专项交办:
                        isDd = true;
                        var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == p.ItemID);
                        if (rs != null) TaskID = rs.TaskID;
                        break;
                }
                var TaskName = "";
                if (p.ItemType == 事项类型.专项交办)
                {
                    var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == p.TaskID);
                    if (t != null) TaskName = t.Name;
                }
                else
                {
                    var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == p.TaskID);
                    if (task != null) TaskName = task.TaskName;
                }

                var LeadUnit = "";
                var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == p.AssignID);
                if (a != null) LeadUnit = a.LeadUnit;
                //关闭通知
                var js = ddService.Notification(new List<string>(), "任务催办", TaskID.ToString(), "任务名称: " + TaskName, msg, pushStep: 推送流程.交办, unitCode: LeadUnit, superId: p.ItemID);
                Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了任务催办通知，返回值：" + msg);
                TaskLogService.AddLog(isDd ? p.ItemID : TaskID, "催办了工作计划(" + p.Measure + ")", true);
            }
            return this.ToJson(new
            {
                success = true
            });
        }

        [User]
        public ActionResult Repeal()
        {
            var SchemeID = Form.GetInt("SchemeID");
            var ret = ctx.Database.ExecuteSql("update Yqd_Scheme set CheckStatus={1},ReturnReason=null,CheckTime=null where SchemeID={0}", SchemeID, (int)审核状态.待审);
            if (ret > 0)
            {
                var p = ctx.Yqd_Scheme.FirstOrDefault(it => it.SchemeID == SchemeID);
                var IsJb = p.ItemType == 事项类型.专项交办;
                TaskLogService.AddLog(IsJb ? p.ItemID : p.TaskID, "撤销了工作方案(" + p.JobTarget + ")", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        public ActionResult Import()
        {
            var fn = Form.GetString("fn", "");
            var TaskID = Form.GetLong("TaskID");
            var AssignID = Form.GetInt("AssignID");
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var attachment = Form.GetString("attachment", "");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;
            //string headtitle = "", text = "";
            var IsJb = false;
            //if (SuperviseID > 0)
            //{
            //    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == ItemID);
            //    if (s != null)
            //    {
            //        headtitle = "领导督导";
            //        text = "督导意见  " + s.Content;
            //    }
            //}
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
                //var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == ItemID);
                //if (c != null)
                //{
                //    headtitle = "领导协调";
                //    text = "协调内容  " + c.Item;
                //}
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
                //var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                //if (s != null)
                //{
                //    headtitle = "精准督查";
                //    text = "存在问题  " + s.Problem;
                //}
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
                //headtitle = "专项交办";
                IsJb = true;
            }
            switch (ItemType)
            {
                case 事项类型.钉办督导:
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                    if (s != null && s.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.协同管理:
                    var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == CoordinateID);
                    if (r != null && r.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.精准督查:
                    var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == eSuperviseID);
                    if (e != null && e.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.专项交办:
                    var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == sSuperviseID);
                    if (rs != null && rs.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
            }
            //ctx.Database.ExecuteSql("Update Yqd_Scheme set IsComplete=0 where AssignID={0}", AssignID);
            var path = Env.ServerRoot.Combine("wwwroot/Client/Yqd/");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            FileInfo file = new FileInfo(path + fn);
            if (file != null)
            {
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets["工作计划"];
                    int rowCount = worksheet.Dimension.Rows;
                    int ColCount = worksheet.Dimension.Columns;
                    var Scheme = new List<dynamic>();
                    var target = "";
                    var JobType = 1;
                    var first = true;
                    var plan = new List<dynamic>();
                    ctx.Yqd_SchemeApproval.Add(new Yqd_SchemeApproval
                    {
                        TaskID = TaskID,
                        AssignID = AssignID,
                        ItemID = ItemID,
                        ItemType = ItemType,
                        Attachment = attachment,
                        Leader = worksheet.Cells[2, 1].Value?.ToString() ?? "",
                        Dept = worksheet.Cells[2, 2].Value?.ToString() ?? "",
                        DeptLeader = worksheet.Cells[2, 3].Value?.ToString() ?? "",
                        Instime = DateTime.Now,
                        EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                        UnitCode = WxUser.LogonInfo.UnitCode
                    });
                    for (var row = 4; row <= rowCount; row++)
                    {
                        var JobTarget = worksheet.Cells[row, 1].Value?.ToString() ?? "";
                        var jtype = worksheet.Cells[row, 5].Value?.ToString() ?? "";
                        var Measure = worksheet.Cells[row, 2].Value?.ToString() ?? "";
                        if (JobTarget == "" && Measure == "") continue;
                        if (JobTarget != "" && first)
                        {
                            target = JobTarget;
                            first = false;
                            JobType = jtype == "节点型" ? 1 : 2;
                        }
                        if (JobTarget != "" && target != JobTarget)
                        {
                            Scheme.Add(new
                            {
                                JobTarget = target,
                                JobType,
                                Plan = plan
                            });
                            target = JobTarget;
                            plan = new List<object>();
                        }
                        var CompleteTime = worksheet.Cells[row, 3].Value?.ToString() ?? "";
                        var CooperativeUnit = worksheet.Cells[row, 4].Value?.ToString() ?? "";
                        plan.Add(new
                        {
                            Measure,
                            CompleteTime,
                            CooperativeUnit
                        });
                    }
                    Scheme.Add(new
                    {
                        JobTarget = target,
                        JobType,
                        Plan = plan
                    });
                    var slst = new List<Yqd_Scheme>();
                    foreach (var s in Scheme)
                    {
                        slst.Add(new Yqd_Scheme
                        {
                            TaskID = TaskID,
                            AssignID = AssignID,
                            ItemID = ItemID,
                            ItemType = ItemType,
                            JobTarget = s.JobTarget,
                            JobType = (工作类型)JobType,
                            CheckStatus = 审核状态.待审,
                            IsComplete = false,
                            Instime = DateTime.Now,
                            EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                            UnitCode = WxUser.LogonInfo.UnitCode
                        });
                    }
                    ctx.Yqd_Scheme.AddRange(slst);
                    var ret = ctx.SaveChanges();
                    if (ret > 0)
                    {
                        var TimeLine = "";
                        var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == AssignID);
                        if (a != null)
                        {
                            TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, a.CompleteLimit, a.Days);
                        }
                        var unit = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
                        var plst = new List<Yqd_JobPlan>();
                        foreach (var s in Scheme)
                        {
                            target = s.JobTarget;
                            var m = slst.FirstOrDefault(it => it.JobTarget == target);
                            var SchemeID = 0;
                            if (m != null) SchemeID = m.SchemeID;
                            var pl = (List<dynamic>)s.Plan;
                            var ps = pl.OrderBy(p => DateTime.Parse(p.CompleteTime));
                            first = true;
                            foreach (var p in ps)
                            {

                                var counit = "";
                                if (!string.IsNullOrWhiteSpace(p.CooperativeUnit))
                                {
                                    var CooperativeUnit = (string)p.CooperativeUnit;
                                    counit = string.Join(",", unit.Where(it => ("," + CooperativeUnit + ",").Contains("," + it.Name + ",")));
                                }
                                var model = new Yqd_JobPlan
                                {
                                    TaskID = TaskID,
                                    AssignID = AssignID,
                                    ItemID = ItemID,
                                    ItemType = ItemType,
                                    SchemeID = SchemeID,
                                    Measure = p.Measure,
                                    CompleteTime = DateTime.Parse(p.CompleteTime),
                                    CooperativeUnit = counit,
                                    PlanStatus = 工作计划状态.未完成,
                                    Instime = DateTime.Now,
                                    EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                                    UnitCode = WxUser.LogonInfo.UnitCode
                                };
                                if (first)
                                {
                                    model.TimeLine = TimeLine;
                                    first = false;
                                }
                                plst.Add(model);
                            }
                        }
                        ctx.Yqd_JobPlan.AddRange(plst);
                        ret = ctx.SaveChanges();
                        if (ret > 0)
                        {
                            TaskLogService.AddLog(IsJb ? ItemID : TaskID, "导入了工作方案", IsJb);
                        }
                    }
                    return this.ToJson(new
                    {
                        success = true,
                        ret
                    });
                }
            }
            return this.ToJson(new
            {
                success = false
            });
        }

        public ActionResult Import2()
        {
            var fn = Form.GetString("fn", "");
            var TaskID = Form.GetLong("TaskID");
            var AssignID = Form.GetInt("AssignID");
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            var attachment = Form.GetString("attachment", "");
            var ItemID = SuperviseID;
            var ItemType = 事项类型.钉办督导;
            //string headtitle = "", text = "";
            var IsJb = false;
            //if (SuperviseID > 0)
            //{
            //    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == ItemID);
            //    if (s != null)
            //    {
            //        headtitle = "领导督导";
            //        text = "督导意见  " + s.Content;
            //    }
            //}
            if (CoordinateID > 0)
            {
                ItemID = CoordinateID;
                ItemType = 事项类型.协同管理;
                //var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == ItemID);
                //if (c != null)
                //{
                //    headtitle = "领导协调";
                //    text = "协调内容  " + c.Item;
                //}
            }
            if (eSuperviseID > 0)
            {
                ItemID = eSuperviseID;
                ItemType = 事项类型.精准督查;
                //var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == ItemID);
                //if (s != null)
                //{
                //    headtitle = "精准督查";
                //    text = "存在问题  " + s.Problem;
                //}
            }
            if (sSuperviseID > 0)
            {
                ItemID = sSuperviseID;
                ItemType = 事项类型.专项交办;
                //headtitle = "专项交办";
                IsJb = true;
            }
            switch (ItemType)
            {
                case 事项类型.钉办督导:
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                    if (s != null && s.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.协同管理:
                    var r = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == CoordinateID);
                    if (r != null && r.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.精准督查:
                    var e = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == eSuperviseID);
                    if (e != null && e.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
                case 事项类型.专项交办:
                    var rs = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == sSuperviseID);
                    if (rs != null && rs.Status == 任务状态.已完成)
                    {
                        return this.ToJson(new
                        {
                            success = true,
                            ret = 0
                        });
                    }
                    break;
            }
            //ctx.Database.ExecuteSql("Update Yqd_Scheme set IsComplete=0 where AssignID={0}", AssignID);
            var path = Env.ServerRoot.Combine("wwwroot/Client/Yqd/");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            FileInfo file = new FileInfo(path + fn);
            if (file != null)
            {
                ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

                    int rowCount = worksheet.Dimension.Rows;
                    int ColCount = worksheet.Dimension.Columns;
                    var Scheme = new List<dynamic>();
                    var target = "";
                    var JobType = 1;
                    var first = true;
                    var plan = new List<dynamic>();
                    ctx.Yqd_SchemeApproval.Add(new Yqd_SchemeApproval
                    {
                        TaskID = TaskID,
                        AssignID = AssignID,
                        ItemID = ItemID,
                        ItemType = ItemType,
                        Attachment = attachment,
                        Leader = worksheet.Cells[2, 1].Value?.ToString() ?? "",
                        Dept = worksheet.Cells[2, 2].Value?.ToString() ?? "",
                        DeptLeader = worksheet.Cells[2, 3].Value?.ToString() ?? "",
                        Instime = DateTime.Now,
                        EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                        UnitCode = WxUser.LogonInfo.UnitCode
                    });
                    for (var row = 4; row <= rowCount; row++)
                    {
                        var JobTarget = worksheet.Cells[row, 1].Value?.ToString() ?? "";
                        var jtype = worksheet.Cells[row, 4].Value?.ToString() ?? "";
                        var jtype2 = worksheet.Cells[row, 5].Value?.ToString() ?? "";
                        var Measure = worksheet.Cells[row, 2].Value?.ToString() ?? "";
                        if (JobTarget == "" && Measure == "") continue;
                        if (JobTarget != "" && first)
                        {
                            target = JobTarget;
                            first = false;
                            JobType = jtype == "节点型" ? 1 : jtype2 == "节点型" ? 1 : 2;
                        }
                        if (JobTarget != "" && target != JobTarget)
                        {
                            Scheme.Add(new
                            {
                                JobTarget = target,
                                JobType,
                                Plan = plan
                            });
                            target = JobTarget;
                            plan = new List<object>();
                        }
                        var CompleteTime = worksheet.Cells[row, 3].Value?.ToString() ?? "";
                        //var CooperativeUnit = worksheet.Cells[row, 4].Value?.ToString() ?? "";
                        plan.Add(new
                        {
                            Measure,
                            CompleteTime
                        });
                    }
                    Scheme.Add(new
                    {
                        JobTarget = target,
                        JobType,
                        CooperativeUnit = "",
                        Plan = plan
                    });

                    var result = new
                    {
                        ProgressInfo = "",
                        Material = new string[] { },
                        SchemeApproval = new
                        {
                            Leader = worksheet.Cells[2, 1].Value?.ToString() ?? "",
                            Dept = worksheet.Cells[2, 2].Value?.ToString() ?? "",
                            DeptLeader = worksheet.Cells[2, 3].Value?.ToString() ?? ""
                        },
                        Scheme = Scheme
                    };
                    return this.ToJson(new
                    {
                        success = true,
                        datas = result
                    });
                }
            }
            return this.ToJson(new
            {
                success = false
            });
        }
    }
}
